package org.bonorsoft.modules.education.controller;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.bonorsoft.common.api.vo.Result;
import org.bonorsoft.common.system.query.QueryGenerator;
import org.bonorsoft.common.util.DateUtils;
import org.bonorsoft.modules.education.entity.EduImportExcel;
import org.bonorsoft.modules.education.entity.EduInfor;
import org.bonorsoft.modules.education.service.IEduInforService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.bonorsoft.common.aspect.annotation.AutoLog;
import org.bonorsoft.common.system.base.controller.BonorController;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

/**
 * @Description: 全市学校信息表
 * @Author: WilliamYe
 * @Date:   2020-11-23
 * @Version: V1.0
 */
@Slf4j
@Controller
@RequestMapping("/education/information")
public class EduInforController extends BonorController<EduInfor, IEduInforService> {
    private String prefix = "education/information";

	@Value(value = "${william.path.excel}")
	private String excelpath;
	
	@Autowired
	private IEduInforService eduInforService;

	/**
	*首页
	*/
	@RequiresPermissions("education:information:view")
    @GetMapping()
    public String index()
    {
     return prefix + "/information";
    }

	/**
	 * 分页列表查询
	 *
	 * @param eduInfor
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "全市学校信息表-分页列表查询")
	@RequiresPermissions("education:information:list")
	@GetMapping(value = "/list")
	@ResponseBody
	public Result<?> queryPageList(EduInfor eduInfor,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<EduInfor> queryWrapper = QueryGenerator.initQueryWrapper(eduInfor, req.getParameterMap());
		Page<EduInfor> page = new Page<EduInfor>(pageNo, pageSize);
		IPage<EduInfor> pageList = eduInforService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

    /**
    * 添加页面
    *
    */
    @GetMapping("/add")
    public String add()
    {
     return prefix + "/add";
    }

	/**
	 * 添加
	 *
	 * @param eduInfor
	 * @return
	 */
	@AutoLog(value = "全市学校信息表-添加")
	@RequiresPermissions("education:information:add")
	@PostMapping(value = "/add")
    @ResponseBody
	public Result<?> add(@Validated EduInfor eduInfor) {
		eduInforService.save(eduInfor);
		return Result.ok("添加成功！");
	}

    /**
    * 编辑页面
    */
	@GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
     mmap.put("editInfo", eduInforService.getById(id));
     return prefix + "/edit";
    }

	/**
	 * 编辑
	 *
	 * @param eduInfor
	 * @return
	 */
	@AutoLog(value = "全市学校信息表-编辑")
	@RequiresPermissions("education:information:edit")
	@PostMapping(value = "/edit")
	@ResponseBody
	public Result<?> edit(@Validated EduInfor eduInfor) {
		eduInforService.updateById(eduInfor);
		return Result.ok("编辑成功!");
	}

	/**
	 * 详细页面
	 */
	@GetMapping("/detail/{id}")
	public String detail(@PathVariable("id") String id, ModelMap mmap)
	{
		mmap.put("detailInfo", eduInforService.getById(id));
		return prefix + "/detail";
	}

	/**
	 * 通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "全市学校信息表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		eduInforService.removeById(id);
		return Result.ok("删除成功!");
	}

	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "全市学校信息表-批量删除")
	@RequiresPermissions("education:information:remove")
	@DeleteMapping(value = "/deleteBatch")
	@ResponseBody
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.eduInforService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "全市学校信息表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		EduInfor eduInfor = eduInforService.getById(id);
		return Result.ok(eduInfor);
	}

  /**
   * 导出excel
   *
   * @param request
   * @param eduInfor
   */
  	@AutoLog(value = "全市学校信息数据-导出excel")
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, EduInfor eduInfor) {
		TemplateExportParams params = new TemplateExportParams(excelpath + "/excel/templateExcel.xls");
		Map<String, Object> map = new HashMap<>();
		params.setHeadingStartRow(2);
		params.setHeadingRows(3);
		int year = DateUtils.getYear();
		map.put("year", year);
		return super.exportXlsByTemplate(params, map, request, eduInfor, EduInfor.class ,"东营市学校信息总览表");
	}

	/**
   * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
	@AutoLog(value = "excel导入全市学校信息数据")
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	@ResponseBody
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
	  String learnType = request.getParameter("learnType");
	  return importMyExcel(request, response, learnType);
	}

  /** 功能描述:自定义excel导入
   *
   * @vison: 1.0.0
   * @Author: WilliamYe
   * @Date: 2020/11/25 16:54
   */
  private Result<?> importMyExcel(HttpServletRequest request, HttpServletResponse response, String learnType) {
	  MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
	  Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
	  for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
		  MultipartFile file = entity.getValue();// 获取上传文件对象
		  ImportParams params = new ImportParams();
		  params.setHeadRows(2);
		  params.setTitleRows(3);
		  try {
			  List<EduImportExcel> list = ExcelImportUtil.importExcel(file.getInputStream(), EduImportExcel.class, params);
			  //update-begin-author:taoyan date:20190528 for:批量插入数据
			  long start = System.currentTimeMillis();
			  List<EduInfor> eduInforList = JSONArray.parseArray(JSON.toJSONString(list), EduInfor.class);
			  eduInforList.forEach(item -> item.setLearnType(learnType));
			  eduInforService.saveBatch(eduInforList);
			  //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
			  //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
			  log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
			  //update-end-author:taoyan date:20190528 for:批量插入数据
			  return Result.ok("文件导入成功！数据行数：" + list.size());
		  } catch (Exception e) {
			  log.error(e.getMessage(), e);
			  return Result.error("文件导入失败:" + e.getMessage());
		  } finally {
			  try {
				  file.getInputStream().close();
			  } catch (IOException e) {
				  e.printStackTrace();
			  }
		  }
	  }
	  return Result.error("文件导入失败！");

  }

	/**
	 * 根据模板自定义导出下载模板
	 * @return
	 */
	@AutoLog(value = "全市学校信息数据-导出模板", operateType = 6)
	@RequestMapping(value = "/importTemplate")
	public ModelAndView importTemplate() {
		TemplateExportParams params = new TemplateExportParams(excelpath + "/excel/templateExcel.xls");
		Map<String, Object> map = new HashMap<>();
		int year = DateUtils.getYear();
		map.put("year", year);
		return super.importTemplateByExcel(params, map, EduInfor.class ,"东营市学校信息总览表");
	}

 }
